package com.xd.springaiagent.tools;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class FileTool {
    @Value("${file.storage.path:src/main/resources/file}")
    private String basePath;

    @Tool(name = "fileSave", description = "save a txt file in localhost")
    public String fileSave(
            @ToolParam(description = "file name", required = true) String fileName,
            @ToolParam(description = "content to save", required = true) String content
    ) {
        // 使用当前时间（格式：yyyyMMdd）作为目录名
        String date = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"))
                .format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        Path dirPath = Paths.get(basePath, date);

        try {
            // 自动创建多级目录
            Files.createDirectories(dirPath);

            // 确保文件名包含 .txt 扩展名
            String finalFileName = appendTxtExtension(fileName);
            Path filePath = dirPath.resolve(finalFileName);

            // 写入文件内容
            Files.write(filePath, content.getBytes(),
                    StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING);

            return "成功保存：" + filePath.toAbsolutePath() + "，内容：" + content;
        } catch (IOException e) {
            return "保存失败：" + e.getMessage();
        }
    }

    private String appendTxtExtension(String fileName) {
        return fileName.endsWith(".txt") ? fileName : fileName + ".txt";
    }
}
